//package com.mce.nebula.controller;
//
//import com.mce.nebula.dto.ApiResponse;
//import com.mce.nebula.dto.TeamRoleCreateRequest;
//import com.mce.nebula.dto.TeamRoleResponse;
//import com.mce.nebula.dto.TeamRolePermissionResponse;
//import com.mce.nebula.entity.Team;
//import com.mce.nebula.entity.TeamRole;
//import com.mce.nebula.entity.TeamRolePermission;
//import com.mce.nebula.security.UserDetailsImpl;
//import com.mce.nebula.service.TeamRoleService;
//import com.mce.nebula.service.TeamService;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.validation.Valid;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.http.ResponseEntity;
//import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.security.core.Authentication;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//import java.util.stream.Collectors;
//
///**
// * 团队角色管理控制器
// */
//@Slf4j
//@RestController
//@RequestMapping("/api/teams/{teamName}/roles")
//@Tag(name = "团队角色管理", description = "团队角色管理相关接口")
//@RequiredArgsConstructor
//public class TeamRoleController {
//
//    private final TeamRoleService teamRoleService;
//    private final TeamService teamService;
//
//    @PostMapping
//    @Operation(summary = "创建团队角色", description = "在指定团队下创建新的角色")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<TeamRoleResponse>> createTeamRole(
//            @PathVariable String teamName,
//            @Valid @RequestBody TeamRoleCreateRequest request,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            String enterpriseId = userDetails.getEnterpriseId();
//
//            TeamRole teamRole = teamRoleService.createTeamRole(request, team.getTenantId(), enterpriseId);
//
//            // 获取角色权限
//            List<TeamRolePermission> permissions = teamRoleService.getRolePermissions(teamRole.getRoleId());
//            TeamRoleResponse response = new TeamRoleResponse(teamRole);
//            response.setPermissions(permissions.stream()
//                .map(TeamRolePermissionResponse::new)
//                .collect(Collectors.toList()));
//
//            return ResponseEntity.ok(ApiResponse.success(response, "角色创建成功"));
//        } catch (Exception e) {
//            log.error("Failed to create team role: {} in team: {}", request.getRoleName(), teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping
//    @Operation(summary = "获取团队角色列表", description = "获取团队下的所有角色")
//    public ResponseEntity<ApiResponse<List<TeamRoleResponse>>> getTeamRoles(
//            @PathVariable String teamName,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            // 检查用户是否在团队中
//            if (!teamService.isUserInTeam(team.getTenantId(), userId)) {
//                throw new RuntimeException("用户不在该团队中");
//            }
//
//            List<TeamRole> teamRoles = teamRoleService.getTenantRoles(team.getTenantId());
//            List<TeamRoleResponse> responses = teamRoles.stream()
//                .map(role -> {
//                    TeamRoleResponse response = new TeamRoleResponse(role);
//                    List<TeamRolePermission> permissions = teamRoleService.getRolePermissions(role.getRoleId());
//                    response.setPermissions(permissions.stream()
//                        .map(TeamRolePermissionResponse::new)
//                        .collect(Collectors.toList()));
//                    return response;
//                })
//                .collect(Collectors.toList());
//
//            return ResponseEntity.ok(ApiResponse.success(responses));
//        } catch (Exception e) {
//            log.error("Failed to get team roles for team: {}", teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @GetMapping("/{roleId}")
//    @Operation(summary = "获取角色详情", description = "获取指定角色的详细信息")
//    public ResponseEntity<ApiResponse<TeamRoleResponse>> getTeamRole(
//            @PathVariable String teamName,
//            @PathVariable String roleId,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            // 获取用户信息
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            Integer userId = userDetails.getId().intValue();
//
//            // 检查用户是否在团队中
//            if (!teamService.isUserInTeam(team.getTenantId(), userId)) {
//                throw new RuntimeException("用户不在该团队中");
//            }
//
//            TeamRole teamRole = teamRoleService.findByRoleId(roleId)
//                .orElseThrow(() -> new RuntimeException("角色不存在"));
//
//            // 检查角色是否属于该团队
//            if (!teamRole.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("角色不属于该团队");
//            }
//
//            // 获取角色权限
//            List<TeamRolePermission> permissions = teamRoleService.getRolePermissions(roleId);
//            TeamRoleResponse response = new TeamRoleResponse(teamRole);
//            response.setPermissions(permissions.stream()
//                .map(TeamRolePermissionResponse::new)
//                .collect(Collectors.toList()));
//
//            return ResponseEntity.ok(ApiResponse.success(response));
//        } catch (Exception e) {
//            log.error("Failed to get team role: {} in team: {}", roleId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @PutMapping("/{roleId}")
//    @Operation(summary = "更新角色", description = "更新角色信息")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<TeamRoleResponse>> updateTeamRole(
//            @PathVariable String teamName,
//            @PathVariable String roleId,
//            @Valid @RequestBody TeamRoleCreateRequest request) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            TeamRole teamRole = teamRoleService.findByRoleId(roleId)
//                .orElseThrow(() -> new RuntimeException("角色不存在"));
//
//            // 检查角色是否属于该团队
//            if (!teamRole.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("角色不属于该团队");
//            }
//
//            TeamRole updatedRole = teamRoleService.updateTeamRole(roleId, request);
//
//            // 获取角色权限
//            List<TeamRolePermission> permissions = teamRoleService.getRolePermissions(roleId);
//            TeamRoleResponse response = new TeamRoleResponse(updatedRole);
//            response.setPermissions(permissions.stream()
//                .map(TeamRolePermissionResponse::new)
//                .collect(Collectors.toList()));
//
//            return ResponseEntity.ok(ApiResponse.success(response, "角色更新成功"));
//        } catch (Exception e) {
//            log.error("Failed to update team role: {} in team: {}", roleId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @DeleteMapping("/{roleId}")
//    @Operation(summary = "删除角色", description = "删除指定的角色")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> deleteTeamRole(
//            @PathVariable String teamName,
//            @PathVariable String roleId) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            TeamRole teamRole = teamRoleService.findByRoleId(roleId)
//                .orElseThrow(() -> new RuntimeException("角色不存在"));
//
//            // 检查角色是否属于该团队
//            if (!teamRole.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("角色不属于该团队");
//            }
//
//            teamRoleService.deleteTeamRole(roleId);
//            return ResponseEntity.ok(ApiResponse.success(null, "角色删除成功"));
//        } catch (Exception e) {
//            log.error("Failed to delete team role: {} in team: {}", roleId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @PostMapping("/{roleId}/permissions")
//    @Operation(summary = "添加角色权限", description = "为角色添加权限")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<TeamRolePermissionResponse>> addRolePermission(
//            @PathVariable String teamName,
//            @PathVariable String roleId,
//            @RequestParam String permissionCode,
//            Authentication authentication) {
//        try {
//            // 获取团队信息
//            Team team = new Team();//teamService.findByTeamName(teamName).orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            TeamRole teamRole = teamRoleService.findByRoleId(roleId)
//                .orElseThrow(() -> new RuntimeException("角色不存在"));
//
//            // 检查角色是否属于该团队
//            if (!teamRole.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("角色不属于该团队");
//            }
//
//            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
//            String enterpriseId = userDetails.getEnterpriseId();
//
//            TeamRolePermission permission = teamRoleService.addRolePermission(roleId, permissionCode, enterpriseId);
//            return ResponseEntity.ok(ApiResponse.success(new TeamRolePermissionResponse(permission), "权限添加成功"));
//        } catch (Exception e) {
//            log.error("Failed to add permission: {} to role: {} in team: {}", permissionCode, roleId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//
//    @DeleteMapping("/{roleId}/permissions/{permissionCode}")
//    @Operation(summary = "删除角色权限", description = "从角色中删除权限")
//    @PreAuthorize("hasRole('ADMIN') or @teamService.isTeamAdmin(#teamName, authentication.principal.id)")
//    public ResponseEntity<ApiResponse<Void>> removeRolePermission(
//            @PathVariable String teamName,
//            @PathVariable String roleId,
//            @PathVariable String permissionCode) {
//        try {
//            // 获取团队信息
//            Team team = teamService.findByTeamName(teamName)
//                .orElseThrow(() -> new RuntimeException("团队不存在"));
//
//            TeamRole teamRole = teamRoleService.findByRoleId(roleId)
//                .orElseThrow(() -> new RuntimeException("角色不存在"));
//
//            // 检查角色是否属于该团队
//            if (!teamRole.getTenantId().equals(team.getTenantId())) {
//                throw new RuntimeException("角色不属于该团队");
//            }
//
//            teamRoleService.removeRolePermission(roleId, permissionCode);
//            return ResponseEntity.ok(ApiResponse.success(null, "权限删除成功"));
//        } catch (Exception e) {
//            log.error("Failed to remove permission: {} from role: {} in team: {}", permissionCode, roleId, teamName, e);
//            return ResponseEntity.badRequest()
//                .body(ApiResponse.error(400, e.getMessage()));
//        }
//    }
//}
//
//
//
//
//
